package fabrica2.persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import fabrica2.excecoes.DAOException;

public abstract class GenericDAOImpl<T> implements GenericDAO<T> {
	private Connection conn;
	private Statement statement;

	public GenericDAOImpl() {
	}

	public abstract T persistir(T element) throws DAOException;
	

	public abstract void remover(T element) throws DAOException;

	protected Connection getConexao() {
		return conn;
	}

	protected boolean conectar() throws DAOException {
		String connectionUrl = "jdbc:sqlserver://localhost:1433;"
				+ "databaseName=FABRICA2;user=sa;password=senha";
		try {

			/* Driver do SQL SERVER */
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(connectionUrl);
			statement = conn.createStatement();
			return true;
		} catch (SQLException e) {
			System.err.println("Sql Exception: " + e.getMessage());
			throw new DAOException();
		} catch (ClassNotFoundException e) {
			System.err.println("Class Not Found Exception");
			throw new DAOException();
		}
	}
	

	protected ResultSet getResultSet(String query) throws DAOException {
		conectar();
		ResultSet rs;
		try {
			rs = statement.executeQuery(query);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOException();
		}
		return rs;
	}
	

	public void execute(String query)throws DAOException  {
		conectar();
		try {
			statement.execute(query);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOException();
		}
		desconectar();
	}

	protected void desconectar() throws DAOException {
		try {
			conn.close();
			statement.close();
		} catch (SQLException e) {
			throw new DAOException();
		}
	}

	protected boolean isConnected() {
		try {
			return !conn.isClosed();
		} catch (SQLException e) {
			System.err.println("Sql Exception");
		}
		return false;
	}

}
